package com.axungu.common;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @author jtoms
 */
@Slf4j
public class OapApiRemote {

    private String oapServer;

    private String appKey;

    private String appSecret;

    public OapApiRemote(String oapServer, String appKey, String appSecret) {
        this.oapServer = oapServer;
        this.appKey = appKey;
        this.appSecret = appSecret;
    }

    public String fetch(Method method, Map<String, String> params) {

        Map<String, String> formData = new LinkedHashMap<>();
        // 系统级参数
        formData.put("appKey", appKey);
        formData.put("locale", "zh_CN");
        formData.put("fromSource", "agent_web");
//        formData.put("Custom-Real-IP", ServletContext.getRemoteIPAddress());
        if (params != null) {
            formData.putAll(params);
        }
        String signValue = null;
        try {
            signValue = this.sign(formData, appSecret);
        } catch (Exception e) {
            log.warn("sign error", e);
        }
        formData.put("sign", signValue);
        Connection connection = Jsoup.connect(oapServer);
        connection.requestBody(JSON.toJSONString(formData));
        connection.data(formData);
        connection.header("Content-Type", "text/html;charset=UTF-8");
        connection.method(method);
        connection.timeout(10000);
        try {
            Response response = connection.ignoreContentType(true).execute();
            log.debug(response.body());
            return response.body();
        } catch (IOException e) {
            return "{\"body\":\"" + e.getMessage() + "\",\"header\":{\"code\":\"" + e.getMessage() + "\",\"message\":\""
                    + e.getMessage() + "\"}}";
        }

    }

    /**
     * 生成签名算法
     *
     * @param paramValues
     * @param secret
     * @return
     */
    private String sign(Map<String, String> paramValues, String secret) throws NoSuchAlgorithmException, UnsupportedEncodingException {

        byte[] sha1Digest = null;
        StringBuilder sb = new StringBuilder();
        List<String> paramNames = new ArrayList<String>(paramValues.size());
        paramNames.addAll(paramValues.keySet());
        Collections.sort(paramNames);

        sb.append(secret);
        for (String paramName : paramNames) {
            sb.append(paramName).append(paramValues.get(paramName));
        }
        sb.append(secret);
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        sha1Digest = md.digest(sb.toString().getBytes("UTF-8"));
        StringBuilder sign = new StringBuilder();

        for (byte b : sha1Digest) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }

        return sign.toString();
    }

}
